﻿using Kingdee.BOS.App.Data;
using Kingdee.BOS.Core.Bill;
using Kingdee.BOS.Core.Bill.PlugIn;
using Kingdee.BOS.Core.Bill.PlugIn.Args;
using Kingdee.BOS.Core.DynamicForm;
using Kingdee.BOS.Core.DynamicForm.PlugIn;
using Kingdee.BOS.Core.DynamicForm.PlugIn.Args;
using Kingdee.BOS.Core.DynamicForm.PlugIn.ControlModel;
using Kingdee.BOS.Core.Metadata;
using Kingdee.BOS.JSON;
using Kingdee.BOS.Orm.DataEntity;
using Kingdee.BOS.Util;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;

namespace RCE.K3.YGJD.Business.PlugIn.SAL.Business
{

    [HotUpdate]
    [Description("销售订单 销售数量小于库存数量")]
    public class SalOrderBusinessPlugIn : AbstractBillPlugIn
    {

        public override void AfterDoOperation(AfterDoOperationEventArgs e)
        {
            base.AfterDoOperation(e);
            if (e.Operation.OperationId == 1 && e.OperationResult.IsSuccess)// 审核成功
            {
                var psfs = this.View.Model.GetValue("F_UIXC_PSFS").ToString();
                if (psfs == "2")
                {

                    DynamicObject billData = this.View.Model.DataObject;

                    string fid = billData["Id"].ToString();

                    string execSql = @"select t2.FID from T_SAL_DELIVERYNOTICEENTRY_LK t
left join T_SAL_DELIVERYNOTICEENTRY t1 on t1.FENTRYID = t.FENTRYID
left join T_SAL_DELIVERYNOTICE t2 on t2.FID = t1.FID
where t.FSBILLID = " + fid;
                    var dataRows = DBUtils.ExecuteDynamicObject(this.Context, execSql);

                    if (dataRows.Count == 0)
                    {
                        return;
                    }
                    var pkId = dataRows[0]["FID"].ToString();
                    var showParameter = new BillShowParameter();
                    showParameter.FormId = "SAL_DELIVERYNOTICE"; // 业务对象标识 
                    showParameter.PageId = Guid.NewGuid().ToString();
                    showParameter.ParentPageId = this.View.PageId;
                    showParameter.NoBusy = true;
                    showParameter.PKey = pkId; // 单据内码  
                    showParameter.OpenStyle.ShowType = ShowType.MainNewTabPage;
                    //showParameter.LayoutId = "00505691-8444-844a-11ec-62f6b54feed5";// 以指定视图打开

                    showParameter.Status = OperationStatus.EDIT; // 编辑模式打开  
                    this.View.ShowForm(showParameter);


                }
            }
        }

        public override void AfterBindData(EventArgs e)
        {
            base.AfterBindData(e);
            var FBillNo = this.View.Model.GetValue("FBillNo");
            if (FBillNo != null && FBillNo.ToString() != "")
                setEntryColor();
        }

        public override void AfterSave(AfterSaveEventArgs e)
        {
            base.AfterSave(e);
            setEntryColor();
        }

        public override void DataChanged(DataChangedEventArgs e)
        {
            base.DataChanged(e);
            if (e.Field.Key.EqualsIgnoreCase("FQty"))
            {

                var FSRCBILLNO = this.View.Model.GetValue("FSRCBILLNO", 0);
                if (FSRCBILLNO == null || FSRCBILLNO.ToString() == "")
                {
                    setEntryColor();
                }
            }
        }



        public void setEntryColor()
        {
            var entityKey = "FSaleOrderEntry";
            var rowCount = this.View.Model.GetEntryRowCount(entityKey);

            var backColor = "#FF0000";
            for (int i = 0; i < rowCount; i++)
            {

                var materialIdObj = this.View.Model.GetValue("FMaterialId", i) as DynamicObject;
                string materialId = "0";
                if (materialIdObj != null)
                    materialId = materialIdObj["Id"].ToString();

                var stockObj = this.View.Model.GetValue("FSOStockId", i) as DynamicObject;
                string stockId = "0";
                if (stockObj != null)
                    stockId = stockObj["Id"].ToString();

                decimal qty = Convert.ToDecimal(this.View.Model.GetValue("FQty", i));

                string sql = $"select isnull(sum(FBASEQTY),0) FBASEQTY from T_STK_INVENTORY where FMATERIALID = '{materialId ?? ""}' and FSTOCKID = '{stockId ?? ""}' ";

                var dataRows = DBUtils.ExecuteDynamicObject(this.Context, sql);

                if (dataRows.Count <= 0)
                {
                    GridSetRowBackcolor(this.View, entityKey, backColor, i);
                    continue;
                }
                decimal invQty = Convert.ToDecimal(dataRows[0]["FBASEQTY"]);
                if (invQty < qty)
                {
                    GridSetRowBackcolor(this.View, entityKey, backColor, i);
                    continue;
                }
                GridSetRowBackcolor(this.View, entityKey, "#EEEEEE", i);
            }
        }

        /// <summary>
        /// 设置表格背景色
        /// </summary>
        /// <param name="view">当前动态表单的View层接口</param>
        /// <param name="entityKey">单据体的标识</param>
        /// <param name="color">颜色代码</param>
        /// <param name="rowIndex">要设置颜色的数据行的行索引</param>
        private static void GridSetRowBackcolor(IDynamicFormView view, string entityKey, string color, string fieldKey, int rowIndex)
        {
            EntryGrid grid = view.GetControl<EntryGrid>(entityKey);
            grid.SetBackcolor(fieldKey, color, rowIndex);
        }

        /// <summary>
        /// 设置表格背景色
        /// </summary>
        /// <param name="view">当前动态表单的View层接口</param>
        /// <param name="entityKey">单据体的标识</param>
        /// <param name="color">颜色代码</param>
        /// <param name="rowIndex">要设置颜色的数据行的行索引</param>
        private static void GridSetRowBackcolor(IDynamicFormView view, string entityKey, string color, int rowIndex)
        {
            var value = new JSONObject();
            value[rowIndex.ToString()] = color;
            EntryGrid grid = view.GetControl<EntryGrid>(entityKey);
            //grid.SetBackcolor("FPrice", "color", rowIndex);
            var jo = new JSONObject();
            jo["backcolor"] = value;
            var formState = view.GetService<IDynamicFormState>();
            formState.AftInvokeControlMethod(grid.ControlAppearance, "UpdateFieldStates", jo);
        }



    }
}
